<?php

namespace App\Models\CacheModel;


use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

class ZlcrAstrExercise extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr_astr_exercise';

    protected $cacheModel = 'astr_admin.question';

    protected $cacheIdKey = 'id';

    /**
     * 开启了缓存
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $this->whereIn('id', $ids);
            } else
            {
                $this->where('t_id', $type[0])->where('level', $type[1]);
            }

            $questionResult = $this->where('status', 1)
                ->order('id ' . $sortType)
                ->column('title,level,t_id,title_img,option_a,option_b,option_c,option_d,answer,option_type,extend,create_time,update_time', 'id');
        }
        catch (\Exception $e)
        {
            Log::write('占星师后台考试问题获取异常：' . $e->getMessage(), 'error', true);
            return [];
        }

        return $questionResult;
    }

    /**
     * 随机获取题目
     * @param int $level 题目级别
     * @param int $num 获取题目数量
     * @param int $type 题目类别    习题类型id  1=> 定制报告考试题目 2=>培训考试题目 3=>问答-星盘 4=>问答-骰子 5=>问答-塔罗
     * @return array
     * @throws \Exception
     */
    public function randomGetQuestionId($level = 1, $num = 0, $type = 1): array
    {
        $data = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $type)
            ->setPage(-1)
            ->setListKeyType($level)// 类型 用于分页 例如 0全部 1待支付 已支付 //
            ->getListPageDataIds(function ($ids = [], $isCache = true, $sortType = 'desc') use ($type, $level)
            {
                try
                {
                    $resData = $this->where('t_id', $type)->where('level', $level)->where('status', 1)->column('id');
                    $data = [];
                    foreach ($resData as $idItem)
                    {
                        $data[$idItem] = ['id' => $idItem];
                    }
                }
                catch (\Exception $e)
                {
                    Log::write('占星师后台考试问题获取异常：' . $e->getMessage(), 'error', true);
                    $data = [];
                }

                return $data;
            });

        if ($data['data'])
        {
            $ids = array_rand($data['data'], $num);
            if (!is_array($ids))
            {
                $ids = [$ids];
            }
        } else
        {
            $ids = [];
        }
        return $ids;
    }

}
